<?php

namespace App\Http\Controllers\Home;

use App\Model\Branch;
use App\Model\BranchTest;
use App\Model\CreateOrder;
use App\Model\Order;
use App\Model\OrderError;
use App\Model\OrderList;
use App\Model\PushOrder;
use App\Model\tel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    // 列表页
    public function index(Request $request)
    {
        $order = Order::orderBy("id","desc")->where(function($query) use($request){
            $orderno =$request->input('orderno');
            $account = $request->input('account');
            if($orderno){
                $query->where('orderno','like','%'.$orderno.'%');
            }
            if($account){
                $query->where('chargeaccount','like','%'.$account.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):20);

        foreach ($order as $k=>$v){
            preg_match('/\d+/',$v['productname'],$price);
            $order[$k]['remainingnumber'] = $price[0];
            $name = Branch::where('id',$v['bid'])->select('username')->first();
            $order[$k]['bid'] = $name['username'];
        }

        $start_time=strtotime(date("Y-m-d",time()));

        $count = Order::where('isok',1) -> sum('remainingnumber');
        $count_false = Db::table('order')->whereRaw('isok = 2')->sum('remainingnumber');
        $count_today = Db::table('order')->whereRaw('isok = 1')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
        $count_today_false = Db::table('order')->whereRaw('isok = 2')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
//        dd($request->input('orderno'));
        return view("home.order.list",compact("order","request","count_today",'count','count_false','count_today_false'));
    }

    //拆单列表
    public function splitlist(Request $request){
        $order = PushOrder::orderBy("id","desc")->where(function($query) use($request){
            $orderno =$request->input('orderno');
            $account = $request->input('account');
            if($orderno){
                $query->where('orderno','like','%'.$orderno.'%');
            }
            if($account){
                $query->where('chargeaccount','like','%'.$account.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):20);
        $start_time=strtotime(date("Y-m-d",time()));

        foreach ($order as $k=>$v){
            $name = Branch::where('id',$v['bid'])->select('username')->first();
            $order[$k]['bid'] = $name['username'];
        }

        $count = PushOrder::where('isok',1) -> sum('remainingnumber');
        $count_false = Db::table('pushorder')->whereRaw('isok = 2')->sum('remainingnumber');
        $count_today = Db::table('pushorder')->whereRaw('isok = 1')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
        $count_today_false = Db::table('pushorder')->whereRaw('isok = 2')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
//        dd($request->input('orderno'));
        return view("home.order.splitlist",compact("order","request","count_today",'count','count_false','count_today_false'));
    }

    //话费列表
    public function calllist(Request $request){
        $order = tel::orderBy("id","desc")->where(function($query) use($request){
            $orderno =$request->input('orderno');
            $account = $request->input('account');
            if($orderno){
                $query->where('orderno','like','%'.$orderno.'%');
            }
            if($account){
                $query->where('chargeaccount','like','%'.$account.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):20);

        foreach ($order as $k=>$v){
            $data = BranchTest::where('id',$v['pid'])->select("username")->first();
            $order[$k]['bid'] = $data['username'];
        }
//        $start_time=strtotime(date("Y-m-d",time()));
//
//        foreach ($order as $k=>$v){
//            $name = Branch::where('id',$v['bid'])->select('username')->first();
//            $order[$k]['bid'] = $name['username'];
//        }
//
//        $count = PushOrder::where('isok',1) -> sum('remainingnumber');
//        $count_false = Db::table('pushorder')->whereRaw('isok = 2')->sum('remainingnumber');
//        $count_today = Db::table('pushorder')->whereRaw('isok = 1')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
//        $count_today_false = Db::table('pushorder')->whereRaw('isok = 2')->whereRaw('buytime >= '.$start_time)->sum('remainingnumber');
//        dd($request->input('orderno'));
//        return view("home.order.splitlist",compact("order","request","count_today",'count','count_false','count_today_false'));
        return view("home.order.calllist",compact("order","request"));
    }

    //问题订单
    public function orderError(Request $request){
        $order = OrderError::orderBy("id","desc")->where(function($query) use($request){
            $orderno =$request->input('orderno');
            $account = $request->input('account');
            if($orderno){
                $query->where('orderno','like','%'.$orderno.'%');
            }
            if($account){
                $query->where('chargeaccount','like','%'.$account.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):20);

        return view("home.order.orderError",compact("order","request"));
    }

    //添加页面
    public function create()
    {
        $flag = true;
        $num = 0;
        $GoodsAllocated = 'DyWb';
        $sign = strtoupper(md5($GoodsAllocated."2Serge#57$768rtv0"));
        $data = "guaji=".$GoodsAllocated."&ts=2&Sign=".$sign;
//        $url = "http://interface.qsios.cn:8136/actionapi/Order/GetOrderRedis";
//        $res = $this->curlGet($url,'post',$data);

        $url = "http://localhost:8000/index/info";

        $res = $this->curlGet($url,'get');
        $res = htmlspecialchars_decode($res);
        $xml=simplexml_load_string($res);

        $order['orderno'] = $xml->Order->OrderNo;
        $order['status'] = $xml->Order->OrderStatus;
        $order['buytime'] = $xml->Order->BuyTime;
        $order['time'] = strtotime('2021/9/15 13:22:01');
        $order['num'] = $xml->Order->BuyNum;
        $order['productid'] = $xml->Order->ProductId;
        $order['productprice'] = $xml->Order->ProductPrice;
        $order['productname'] = $xml->Order->ProductName;
        $order['producttype'] = $xml->Order->ProductType;
        $order['templateid'] = $xml->Order->TemplateId;
        $order['chargeaccount'] = $xml->Order->ChargeAccount;
        $order['chargetype'] = $xml->Order->ChargeType;
        $order['jsitid'] = $xml->Order->JSitid;
        $order['gsitid'] = $xml->Order->GSitid;
        $order['buyerip'] = $xml->Order->BuyerIp;
        $order['remainingnumber'] = $xml->Order->RemainingNumber;
        $order['customerorderno'] = $xml->Order->CustomerOrderNo;
        $order['extractsignid'] = $xml->Order->ExtractSignId;
         Order::create($order);

        echo "获取了".++$num."次，每秒获取1次";

    }

    public function curlGet($url,$method,$post_data = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        } elseif ($method == 'get') {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function show($id){

    }

    //添加操作
    public function store(Request $request)
    {

        $res = $request->post("postData");
        $xml=simplexml_load_string($res);
        $order['orderno'] = $xml->Order->OrderNo;
        $order['status'] = $xml->Order->OrderStatus;
        $order['buytime'] = $xml->Order->BuyTime;
        $order['num'] = $xml->Order->BuyNum;
        $order['productid'] = $xml->Order->ProductId;
        $order['productprice'] = $xml->Order->ProductPrice;
        $order['productname'] = $xml->Order->ProductName;
        $order['producttype'] = $xml->Order->ProductType;
        $order['templateid'] = $xml->Order->TemplateId;
        $order['chargeaccount'] = $xml->Order->ChargeAccount;
        $order['chargetype'] = $xml->Order->ChargeType;
        $order['jsitid'] = $xml->Order->JSitid;
        $order['gsitid'] = $xml->Order->GSitid;
        $order['buyerip'] = $xml->Order->BuyerIp;
        $order['remainingnumber'] = $xml->Order->RemainingNumber;
        $order['customerorderno'] = $xml->Order->CustomerOrderNo;
        $order['extractsignid'] = $xml->Order->ExtractSignId;
        $res = Order::create($order);
        if($res){
            return 'success';
        }else{
            return 'error';
        }
    }

    //返回修改页面
    public function edit($id)
    {
        $order = Order::find($id);
        return view("home.order.edit",compact('order'));
    }

    //执行修改操作
    public function update(Request $request, $id)
    {

        $order = $request -> all();

        $res = Order::where("id",$id)->update($order);
        if($res){
            echo json_encode([
                "code"=>1,
                "msg"=>"success"
            ]);
        }else{
            echo json_encode([
                "code"=>0,
                "msg"=>"error"
            ]);
        }
    }

    //删除操作
    public function destroy(Request $request,$id)
    {
        $user = Order::find($id);
        $res = $user->delete();
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    //批量删除
    public function delAll(Request $request){
        $res = Order::destroy($request->input('ids'));
        if($res){
            $data = array(
                "status"=>0,
                "message"=>"删除成功"
            );
        }else{
            $data = array(
                "status"=>1,
                "message"=>"删除失败"
            );
        }
        return $data;
    }

    //导出记录
    public function orderlist(Request $request){
        $order = OrderList::orderBy("id","desc")->where(function($query) use($request){
            $orderno =$request->input('username');
            if($orderno){
                $query->where('orderno','like','%'.$orderno.'%');
            }
        })->paginate($request->input("num")?$request->input("num"):20);
        return view("home.order.orderlist",compact("order","request"));
    }

    //创建订单页面
    public function createorder(Request $request){

        $order = CreateOrder::orderBy("id","desc")->where(function($query) use($request){
        $orderno =$request->input('orderno');
        $account = $request->input('account');
        if($orderno){
            $query->where('orderno','like','%'.$orderno.'%');
        }
        if($account){
            $query->where('chargeaccount','like','%'.$account.'%');
        }
    })->paginate($request->input("num")?$request->input("num"):20);

        foreach ($order as $k=>$v){
            $data = BranchTest::where('id',$v['pid'])->select("username")->first();
            $order[$k]['bid'] = $data['username'];
        }
        return view("home.order.createorder",compact("order","request"));
    }

    public function addorder(){
        return view("home.order.add");
    }

    public function doaddorder(Request $request){
        try {
            $post = $request->post();
            $info['chargeaccount'] = $post['chargeaccount'];
            $info['price'] = $post['price'];
            $info['ip'] = $post['ip'];
            $info['order'] = date('Ymd').str_pad(mt_rand(1,99999),5,'0',STR_PAD_LEFT);
            $url = 'http://asmile.cn:7006/order/'.$info['order'].'/'.$info['chargeaccount'].'/'.$info['price'].'/'.$info['ip'];
            $res = curlGet($url);
            sleep(15);
            $data = json_decode($res);
            if($data->url !== ""){
                $info['url'] = $data->url;
            }
            $res = CreateOrder::create($info);
            if($res){
                echo json_encode([
                    "code"=>1,
                    "msg"=>"success",
                    "data"=>$res
                ]);
            }else{
                echo json_encode([
                    "code"=>0,
                    "msg"=>"error",
                    "data"=>$res
                ]);
            }
        }catch (\Exception $e){
            echo $e->getMessage();
        }
    }
}
